﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using FDFtpSync.Core;
using FDFtpSync.Entities;
using FDFtpSync.Entities.Extensions;
using Topshelf;

namespace FDFtpSync.Client
{
    /*
     * CreatedOn: 2018-05-23
     * CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// window服务
    /// </summary>
    public class FileSyncService : ServiceControl
    {
        private readonly IFileSyncServer _fileSyncServer;

        public FileSyncService()
        {
            _fileSyncServer = SyncContext.Current.Container.Resolve<IFileSyncServer>(); //new HttpFileSyncServer();//FtpFileSyncServer();
        }

        public bool Start(HostControl hostControl)
        {
            try
            {
                _fileSyncServer.Start();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                SyncContext.Current.Logger.Value.Error("", e);
            }
            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            _fileSyncServer.Stop();
            return true;
        }

        protected string GetFileMd5(string path, string pathName)
        {
            using (var client = new HttpClient())
            {
                var content = new StringContent(new { FileName = path, PathName = pathName }.ToJson());
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var res = client.PostAsync(SyncContext.Current.GetSyncConfig<ClientSyncConfig>().FileMd5Url, content).Result.Content.ReadAsStringAsync().Result;
                var apiRes = res.FromJson<ApiResult<string>>();
                if (apiRes.Code == 0)
                {
                    return apiRes.Result;
                }

                return string.Empty;
            }
        }


    }
}
